package cn.ailearn.security.filter;

import cn.ailearn.module.service.UsersService;
import cn.ailearn.security.details.MySysUserDetails;
import cn.ailearn.utils.JWTUtils;
import cn.ailearn.utils.RedisUtils;
import cn.ailearn.utils.StringUtils;
import cn.hutool.json.JSONUtil;
import io.jsonwebtoken.Claims;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;
import java.util.Objects;

/**
 * @ClassName JwtAuthenticationTokenFilter
 * @Description jwt认证过滤器,每次请求只过滤一次
 * todo 待优化
 * @Author WDEMO
 * @Date 2025/10/22 16:40
 */
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Autowired
    private RedisUtils redisUtils;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        //获取token
        String token = request.getHeader("token");
        if (StringUtils.isEmpty(token)){
            filterChain.doFilter(request,response);
            return;
        }

        //解析token
        Claims claims = JWTUtils.parseToken(token);
        if (Objects.isNull(claims)){
            throw new RuntimeException("token非法");
        }

        String userId = claims.get("user_id").toString();
        //判断缓存中是否有的用户信息
        String userInfoRedisKey = UsersService.getUserInfoRedisKey(Long.valueOf(userId));
        String userDetailObj = redisUtils.getCacheObject(userInfoRedisKey).toString();

        if (Objects.isNull(userDetailObj)){
            throw new RuntimeException("用户未登录");
        }
        MySysUserDetails mySysUserDetails = JSONUtil.toBean(userDetailObj, MySysUserDetails.class);

        //创建认证对象，设置到SecurityContextHolder中
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(mySysUserDetails, null, mySysUserDetails.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);

        //todo 可以优化
//        BaseContext.setCurrentId(userInfo.getId());

        //放行
        filterChain.doFilter(request,response);
    }
}
